import 'package:auto_route/auto_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_student/config/app_router.dart';
import 'package:provider_student/screens/login/login_input_phone.dart';
import '../../providers/auth_provider.dart';
// import '../../utils/validators.dart';

@RoutePage()
class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _obscurePassword = true;

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  void _login() async {
    if (_formKey.currentState?.validate() ?? false) {
      final username = _usernameController.text.trim();
      final password = _passwordController.text.trim();

      final authProvider = Provider.of<AuthProvider>(context, listen: false);
      final success = await authProvider.login(username, password);

      if (!success && mounted) {
        // 显示错误信息
        showCupertinoDialog(
          context: context,
          builder:
              (context) => CupertinoAlertDialog(
                title: const Text('登录失败'),
                content: Text(authProvider.errorMessage ?? '未知错误'),
                actions: [
                  CupertinoDialogAction(
                    child: const Text('确定'),
                    onPressed: () => Navigator.of(context).pop(),
                  ),
                ],
              ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(middle: Text('登录')),
      child: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // Logo或应用名称
                const Icon(
                  CupertinoIcons.person_circle_fill,
                  size: 80,
                  color: CupertinoColors.activeBlue,
                ),
                const SizedBox(height: 24),

                // 用户名输入框
                CupertinoTextField(
                  controller: _usernameController,
                  placeholder: '用户名',
                  prefix: const Padding(
                    padding: EdgeInsets.only(left: 10),
                    child: Icon(
                      CupertinoIcons.person,
                      color: CupertinoColors.systemGrey,
                    ),
                  ),
                  padding: const EdgeInsets.symmetric(
                    vertical: 12,
                    horizontal: 10,
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(color: CupertinoColors.systemGrey4),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  keyboardType: TextInputType.emailAddress,
                  autocorrect: false,
                ),
                const SizedBox(height: 16),

                // 密码输入框
                CupertinoTextField(
                  controller: _passwordController,
                  placeholder: '密码',
                  prefix: const Padding(
                    padding: EdgeInsets.only(left: 10),
                    child: Icon(
                      CupertinoIcons.lock,
                      color: CupertinoColors.systemGrey,
                    ),
                  ),
                  suffix: Padding(
                    padding: const EdgeInsets.only(right: 10),
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          _obscurePassword = !_obscurePassword;
                        });
                      },
                      child: Icon(
                        _obscurePassword
                            ? CupertinoIcons.eye_slash
                            : CupertinoIcons.eye,
                        color: CupertinoColors.systemGrey,
                      ),
                    ),
                  ),
                  padding: const EdgeInsets.symmetric(
                    vertical: 12,
                    horizontal: 10,
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(color: CupertinoColors.systemGrey4),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  obscureText: _obscurePassword,
                ),
                const SizedBox(height: 24),

                // 登录按钮
                Consumer<AuthProvider>(
                  builder: (context, auth, child) {
                    final isLoading = auth.status == AuthStatus.authenticating;
                    return CupertinoButton.filled(
                      onPressed: isLoading ? null : _login,
                      child:
                          isLoading
                              ? const CupertinoActivityIndicator()
                              : const Text('登录'),
                    );
                  },
                ),

                const SizedBox(height: 16),

                // 提示信息
                const Center(
                  child: Text(
                    '提示：用户名 test，密码 123456',
                    style: TextStyle(color: CupertinoColors.systemGrey),
                  ),
                ),

                SizedBox(height: 50),
                TextButton(
                  onPressed:
                      () => {
                        // context.pushRoute(PhoneLoginScreen());
                        context.router.push(const PhoneLoginRoute()),
                      },
                  child: Text("test跳转"),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
